// socket.js
const socketIO = require("socket.io");
function generateUniqueRoomId(sender_id, receiver_id) {
    // 使用字符串排序来确保房间ID的唯一性
    const sortedIds = [sender_id, receiver_id].sort();
    return sortedIds.join("-");
}

function setupSocket(server) {
    const io = socketIO(server, {
        allowEIO3: true,
        cors: {
            origin: "*",
            methods: ["GET", "POST"]
        }
    });
    io.on("connection", (socket) => {
        console.log("a user connected");

        socket.on("joinRoom", (room) => {
            console.log(room);
            socket.join(room); // 加入房间
        });

        socket.on("chat content", ({ content, sender_id, receiver_id, room }) => {
            socket.to(room).emit("chat content", { content, sender_id, receiver_id });
        });
        socket.on("chat all", ({ content, sender_id, receiver_id }) => {
            io.emit("chat all", { content, sender_id, receiver_id });
        });
        socket.on("disconnect", () => {
            console.log("user disconnected");
        });

        socket.on("contact", ({ sender_id, receiver_id, content, send_time }) => {
            const room = generateUniqueRoomId(sender_id, receiver_id);
            socket.join(room); // 发送者加入房间
            socket.to(room).emit("chat content", { content, sender_id, receiver_id, room, send_time }); // 只发送给接收者
            io.emit("chat all", { content, sender_id, receiver_id, send_time });
        });
    });

    return io;
}

module.exports = setupSocket;